package cn.tansanqinger.controller.updata;

import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用于教师注册页面信息
 * @author C3H2
 * @time 11月
 */
@Controller
@RequestMapping("/login/register/teacher")
public class UploadPicturesController {
	
	/**
	 * 上传图片
	 * @param file
	 * @return
	 */
	@RequestMapping("/upload/{count}")
	@ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, @PathVariable("count") String count, HttpServletRequest request) {
        if (file.isEmpty()) return "上传失败，请选择文件";
		try {
	        String fileName = UUID.randomUUID().toString().replaceAll("-", "")+"."+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
	        File upload = new File(System.getProperty("user.dir"),"/src/main/resources/resources/images/upload/teacher/"+fileName);
	        if(!upload.exists()) upload.mkdirs();
	        file.transferTo(upload);
	        request.getSession().setAttribute("count"+count, fileName);
	        return fileName;
		} catch (Exception e) {}
        return "上传失败！";
    }
	
	@RequestMapping("/upload1")
	@ResponseBody
    public String upload1(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) return "上传失败，请选择文件";
		try {
	        String fileName = UUID.randomUUID().toString().replaceAll("-", "")+"."+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
	        File upload = new File(System.getProperty("user.dir"),"/src/main/resources/resources/images/upload/teacher/"+fileName);
	        if(!upload.exists()) upload.mkdirs();
	        file.transferTo(upload);
	        return fileName;
		} catch (Exception e) {}
        return "上传失败！";
    }
	
	/**
	 * 回显图片
	 * @param id
	 * @return
	 */
	@RequestMapping("/download/{id}")
	@ResponseBody
	public byte[] imageMessage(@PathVariable("id")String id) {
		byte[] bytes = null ;
		try {
			File file = new File(System.getProperty("user.dir"),"/src/main/resources/resources/images/upload/teacher/"+id);
			if (!file.exists()) {
				System.err.println("文件错误");
			}
			@SuppressWarnings("resource")
			FileInputStream inputStream = new FileInputStream(file);
//			int length = inputStream.available();
			bytes = new byte[inputStream.available()];
	        inputStream.read(bytes);
		} catch (Exception e) {}
		return bytes;
	}
}
